const db = require('../config/database');
const wechatPay = require('../utils/wechatPay');
const moment = require('moment');
const logger = require('../utils/logger');
const axios = require('axios');
const config = require('../config/config');

class PayController {
  // 创建支付订单
  async createOrder(req, res) {
    // 从JWT token中获取userId（通过中间件）
    const userId = req.user ? req.user.id : req.body.userId;
    const { productId, code, specInfo, price } = req.body;

    // 完整的请求参数日志
    console.log('========== 创建订单请求参数 ==========');
    console.log('完整请求体:', JSON.stringify(req.body, null, 2));
    console.log('====================================');

    logger.info('创建支付订单请求', { productId, userId, hasSpec: !!specInfo, price: price });

    // 参数验证
    if (!productId || !userId) {
      logger.warn('创建订单参数不完整', { productId, userId });
      return res.json({ success: false, message: '参数不完整，请先登录' });
    }

    try{
      // 检查用户是否是游客（游客不能支付）
      if (req.user && req.user.is_guest === 1) {
        logger.warn('游客尝试支付被拒绝', { userId });
        return res.json({ 
          success: false, 
          message: '游客不能支付，请先登录账号或注册账号' 
        });
      }

      // 查询商品信息
      const [products] = await db.query(
        'SELECT * FROM products WHERE id = ? AND status = 1',
        [productId]
      );

      if (products.length === 0) {
        logger.warn('商品不存在', { productId });
        return res.json({ success: false, message: '商品不存在或已下架' });
      }

      const product = products[0];
      const orderNo = `WX${Date.now()}${Math.floor(Math.random() * 10000)}`;
      
      // 使用规格价格或商品原价（确保是数字类型）
      const finalPrice = parseFloat(price || product.price);
      const totalFee = Math.floor(finalPrice * 100); // 转为分
      
      // 调试日志
      console.log('========== 价格调试信息 ==========');
      console.log('前端传递的price:', price, '类型:', typeof price);
      console.log('商品原价:', product.price, '类型:', typeof product.price);
      console.log('最终使用价格:', finalPrice, '类型:', typeof finalPrice);
      console.log('微信支付金额(分):', totalFee);
      console.log('================================');

      logger.pay('创建订单', {
        orderNo,
        productName: product.name,
        productPrice: product.price,
        specPrice: price,
        finalPrice: finalPrice,
        totalFee: totalFee,
        userId
      });

      // 获取用户的openid（用于微信支付）
      let userOpenid = null;
      
      // 1. 先从数据库查询用户是否已有openid
      const [users] = await db.query(
        'SELECT openid FROM users WHERE id = ?',
        [userId]
      );
      
      if (users.length > 0 && users[0].openid) {
        userOpenid = users[0].openid;
      } else if (code) {
        // 2. 如果数据库没有openid，但前端传了code，则用code换取openid
        try {
          const wxResponse = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
            params: {
              appid: config.wechat.appId,
              secret: config.wechat.appSecret,
              js_code: code,
              grant_type: 'authorization_code'
            }
          });

          if (!wxResponse.data.errcode && wxResponse.data.openid) {
            userOpenid = wxResponse.data.openid;
            
            // 保存openid到用户账号（可选，用于后续支付）
            await db.query(
              'UPDATE users SET openid = ?, updated_at = NOW() WHERE id = ?',
              [userOpenid, userId]
            );
            
            logger.success('通过code换取openid成功', { userId, openid: userOpenid });
          } else {
            logger.warn('通过code换取openid失败', { errcode: wxResponse.data.errcode, errmsg: wxResponse.data.errmsg });
          }
        } catch (error) {
          logger.error('调用微信接口换取openid失败', { error: error.message });
        }
      }
      
      // 3. 如果还是没有openid，返回错误
      if (!userOpenid) {
        logger.warn('用户无法获取openid，无法使用微信支付', { userId, hasCode: !!code });
        return res.json({ 
          success: false, 
          message: '无法获取微信支付凭证，请重试' 
        });
      }

      // 创建订单（V1.0.2 支持规格信息）
      await db.query(
        'INSERT INTO orders (order_no, user_id, product_id, openid, product_name, spec_info, product_price, total_fee, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)',
        [orderNo, userId, productId, userOpenid, product.name, specInfo || null, finalPrice, totalFee]
      );

      // 调用微信统一下单
      console.log('⚠️⚠️⚠️ 即将调用微信支付 ⚠️⚠️⚠️');
      console.log('订单号:', orderNo);
      console.log('支付金额(分):', totalFee);
      console.log('支付金额(元):', totalFee / 100);
      console.log('⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️⚠️');
      
      const result = await wechatPay.unifiedOrder({
        body: product.name,
        outTradeNo: orderNo,
        totalFee: totalFee,
        openid: userOpenid,
        ip: req.ip
      });

      // 记录日志
      await db.query(
        'INSERT INTO pay_logs (order_no, type, content) VALUES (?, ?, ?)',
        [orderNo, 'request', JSON.stringify(result)]
      );

      if (result.return_code === 'SUCCESS' && result.result_code === 'SUCCESS') {
        const payParams = wechatPay.generatePayParams(result.prepay_id);
        logger.success('订单创建成功', { orderNo, prepayId: result.prepay_id });
        
        return res.json({
          success: true,
          message: '订单创建成功',
          data: {
            orderNo,
            payParams
          }
        });
      } else {
        logger.error('微信统一下单失败', {
          orderNo,
          returnCode: result.return_code,
          resultCode: result.result_code,
          errCode: result.err_code,
          errCodeDes: result.err_code_des
        });
        
        return res.json({
          success: false,
          message: result.err_code_des || '创建订单失败'
        });
      }
    } catch (error) {
      logger.error('创建订单异常', {
        error: error.message,
        stack: error.stack,
        productId,
        userId
      });
      return res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }

  // 支付回调
  async notify(req, res) {
    logger.pay('收到支付回调');
    
    try {
      const xmlData = req.body;
      const data = await wechatPay.xmlToObject(xmlData);
      const payData = data.xml;

      logger.pay('支付回调数据', {
        orderNo: payData.out_trade_no,
        transactionId: payData.transaction_id,
        returnCode: payData.return_code,
        resultCode: payData.result_code
      });

      // 记录回调日志到数据库
      await db.query(
        'INSERT INTO pay_logs (order_no, type, content) VALUES (?, ?, ?)',
        [payData.out_trade_no, 'notify', JSON.stringify(payData)]
      );

      // 验证签名
      if (!wechatPay.verifyNotifySign(payData)) {
        logger.error('支付回调签名验证失败', { orderNo: payData.out_trade_no });
        return res.send(wechatPay.objectToXml({
          return_code: 'FAIL',
          return_msg: '签名验证失败'
        }));
      }

      // 验证支付结果
      if (payData.return_code === 'SUCCESS' && payData.result_code === 'SUCCESS') {
        // 更新订单状态为已支付（无论是否已更新，都尝试发货）
        const [updateResult] = await db.query(
          'UPDATE orders SET status = 1, transaction_id = ?, pay_time = ? WHERE order_no = ?',
          [payData.transaction_id, moment().format('YYYY-MM-DD HH:mm:ss'), payData.out_trade_no]
        );

        logger.success('订单支付成功，状态已更新', {
          orderNo: payData.out_trade_no,
          transactionId: payData.transaction_id,
          affectedRows: updateResult.affectedRows
        });

        // 自动发货：查询订单对应的商品，获取网盘地址
        const [orders] = await db.query(
          'SELECT product_id, delivery_status FROM orders WHERE order_no = ?',
          [payData.out_trade_no]
        );

        if (orders.length > 0 && orders[0].product_id) {
          const productId = orders[0].product_id;
          const deliveryStatus = orders[0].delivery_status;
          
          // 如果还未发货，则尝试自动发货
          if (!deliveryStatus || deliveryStatus === 0) {
            // 查询商品的网盘地址
            const [products] = await db.query(
              'SELECT download_url FROM products WHERE id = ?',
              [productId]
            );

            if (products.length > 0 && products[0].download_url) {
              const downloadUrl = products[0].download_url;
              
              // 更新订单发货信息（自动发货）
              const [deliveryResult] = await db.query(
                'UPDATE orders SET delivery_content = ?, delivery_status = 1, delivery_time = NOW() WHERE order_no = ?',
                [downloadUrl, payData.out_trade_no]
              );

              logger.success('订单自动发货成功', {
                orderNo: payData.out_trade_no,
                downloadUrl: downloadUrl,
                affectedRows: deliveryResult.affectedRows
              });
            } else {
              logger.warn('商品没有配置网盘地址，无法自动发货', {
                orderNo: payData.out_trade_no,
                productId: productId
              });
            }
          } else {
            logger.info('订单已发货，跳过自动发货', {
              orderNo: payData.out_trade_no,
              deliveryStatus: deliveryStatus
            });
          }
        } else {
          logger.warn('订单找不到商品ID，无法自动发货', {
            orderNo: payData.out_trade_no
          });
        }
      }

      // 返回成功响应给微信
      logger.pay('支付回调处理完成，返回SUCCESS给微信');
      res.send(wechatPay.objectToXml({
        return_code: 'SUCCESS',
        return_msg: 'OK'
      }));
    } catch (error) {
      logger.error('支付回调处理异常', {
        error: error.message,
        stack: error.stack
      });
      res.send(wechatPay.objectToXml({
        return_code: 'FAIL',
        return_msg: '处理失败'
      }));
    }
  }

  // 查询支付结果
  async queryPayment(req, res) {
    const { orderNo } = req.params;

    logger.info('查询支付结果', { orderNo });

    try {
      const result = await wechatPay.queryOrder(orderNo);

      logger.info('微信支付查询结果', {
        orderNo,
        tradeState: result.trade_state
      });

      if (result.return_code === 'SUCCESS' && result.result_code === 'SUCCESS') {
        // 如果订单已支付，更新本地订单状态
        if (result.trade_state === 'SUCCESS') {
          const [updateResult] = await db.query(
            'UPDATE orders SET status = 1, transaction_id = ?, pay_time = ? WHERE order_no = ?',
            [result.transaction_id, moment().format('YYYY-MM-DD HH:mm:ss'), orderNo]
          );
          
          if (updateResult.affectedRows > 0) {
            logger.success('查询发现订单已支付，状态已同步', { orderNo });
          }

          // 自动发货：如果订单还未发货，则自动发货（无论是否更新了状态）
          const [orders] = await db.query(
            'SELECT product_id, delivery_status FROM orders WHERE order_no = ?',
            [orderNo]
          );

          if (orders.length > 0 && orders[0].product_id && (!orders[0].delivery_status || orders[0].delivery_status === 0)) {
            const productId = orders[0].product_id;
            
            // 查询商品的网盘地址
            const [products] = await db.query(
              'SELECT download_url FROM products WHERE id = ?',
              [productId]
            );

            if (products.length > 0 && products[0].download_url) {
              const downloadUrl = products[0].download_url;
              
              // 更新订单发货信息（自动发货）
              await db.query(
                'UPDATE orders SET delivery_content = ?, delivery_status = 1, delivery_time = NOW() WHERE order_no = ?',
                [downloadUrl, orderNo]
              );

              logger.success('订单自动发货成功（查询支付结果时）', {
                orderNo: orderNo,
                downloadUrl: downloadUrl
              });
            } else {
              logger.warn('商品没有配置网盘地址，无法自动发货（查询支付结果时）', {
                orderNo: orderNo,
                productId: productId
              });
            }
          }
        }

        return res.json({
          success: true,
          data: {
            tradeState: result.trade_state,
            tradeStateDesc: result.trade_state_desc
          }
        });
      } else {
        return res.json({
          success: false,
          message: result.err_code_des || '查询失败'
        });
      }
    } catch (error) {
      logger.error('查询支付结果异常', {
        error: error.message,
        orderNo
      });
      return res.json({ success: false, message: '系统错误，请稍后重试' });
    }
  }
}

module.exports = new PayController();


